import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/ui/pages/personalCenterPages/representation/model/up_image_entity.dart';
import 'package:flutter_juwo/ui/pages/photoHero/PhotoHero.dart';
import 'package:flutter_juwo/ui/pages/photoHero/showBigImage.dart';
import 'package:flutter_juwo/ui/res/strings.dart';
import 'package:flutter_juwo/ui/utils/image_compress_utils.dart';
import 'package:flutter_juwo/ui/utils/select_pic.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'LoadingDialog.dart';
import 'judje_dialog.dart';

///封装选择图片的组件
///@num 传入最大图片数
///@onComlete 完成时回调
class SelectPicWidget extends StatefulWidget {
  int num;
  Function(List<String>) onComplete;

  SelectPicWidget(this.num, this.onComplete);

  @override
  _SelectPicWidgetState createState() => _SelectPicWidgetState();
}

class _SelectPicWidgetState extends State<SelectPicWidget> {
  List<File> imageFiles = [];
  List<String> imgUrls = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return getPicList();
  }

  getPicList() {
    if (imageFiles.length <= 0) {
      return Container(
        alignment: Alignment.centerLeft,
        child: getImageAdd(),
      );
    } else {
      return GridView.count(
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        //水平子Widget之间间距
        crossAxisSpacing: ScreenUtil().setWidth(30),
        //垂直子Widget之间间距
        mainAxisSpacing: 5.0,
        //GridView内边距
        padding: EdgeInsets.all(2.0),
        //一行的Widget数量
        crossAxisCount: 4,
        //子Widget宽高比例
        childAspectRatio: 1.0,
        //子Widget列表
        children: getWidgetList(),
      );
    }
  }

  List<Widget> getWidgetList() {
    if (imgUrls.length == widget.num) {
      return imageFiles.map((item) => getItemContainer(item)).toList();
    } else {
      return imageFiles.map((item) => getItemContainer(item)).toList()
        ..add(getImageAdd());
    }
  }

  Widget getItemContainer(File url) {
    return Container(
        child: Stack(
      children: <Widget>[
        PhotoHero(
            photo: url,
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => ShowBigImagePage(url)),
              );
            },
            width: 300),
        Positioned(
            left: 40.0,
            right: 0,
            top: 0.0,
            child: InkWell(
              onTap: () {
                setState(() {
                  int index = imageFiles.indexOf(url);
                  imgUrls.removeAt(index);
                  imageFiles.remove(url);
                  widget.onComplete(imgUrls);
                });
              },
              child: Image.asset(
                Utils.getImgPath('icon_delete01'),
                width: 20.0,
                height: 20.0,
              ),
            ))
      ],
    ));
  }

  getImageAdd() {
    return InkWell(
      onTap: () {
        getImage();
      },
      child: SelectPic.selectPic,
    );
  }

  Future getImage() async {
      // 申请权限
      Map<PermissionGroup, PermissionStatus> permissions =
          await PermissionHandler()
              .requestPermissions([PermissionGroup.storage]);

      // 申请结果  权限检测
      PermissionStatus permission = await PermissionHandler()
          .checkPermissionStatus(PermissionGroup.storage);

      if (permission == PermissionStatus.granted) {
        //权限申请通过
        var image = await ImagePicker.pickImage(source: ImageSource.gallery);
        if (image != null) {
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return LoadingDialog(
                  text: "上传中",
                );
              });
          _upLoadImage(image); //上传图片
        }

      } else {

        showElasticDialog(
            context: context,
            builder: (BuildContext context) {
              return JudjeDialog(
                title: "没有访问存储权限",
                value:
                Strings.NO_PERMISSION_MSG,
                onPressed: ()async {
                  NavigatorUtils.goBack(context);
                  //权限申请被拒绝！
                  bool isOpened = await PermissionHandler().openAppSettings();
                  if(isOpened){
                    print("打开设置页面");
                  }else{
                    ToastUtil.showShortToast("");
                  }
                },
              );
            });
      }
  }

  _upLoadImage(File image) async {
    File result = await CompressImage.testCompressAndGetFile(image, image.path);
    String path = result.path;
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    FormData formData =
        new FormData.from({"pic": new UploadFileInfo(new File(path), name)});
    DioManager.getInstance().post(Api.USER_UPLODIMG, formData, (json) {
      UpImageEntity entity = UpImageEntity.fromJson(json);

      ///上传失败
      if (entity == null) {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
        return;
      }
      if (entity.status != "200") {
        ToastUtil.showShortErrToast(entity.message);
        return;
      }

      ///上传 成功 显示图片
      if (entity.status == "200") {
        imageFiles.add(image);
        imgUrls.add(entity.data);
        widget.onComplete(imgUrls);
        setState(() {});
      }
      NavigatorUtils.goBack(context);

      print("上传成功：$json");
    }, (err) {
      ToastUtil.showShortToast(Api.ERR_TIME_OUT);
      NavigatorUtils.goBack(context);
    });
  }
}
